package com.mmall.mmall002.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mmall.mmall002.entity.User;
import com.mmall.mmall002.entity.UserAddress;
import com.mmall.mmall002.service.CartService;
import com.mmall.mmall002.service.UserAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 龙菲
 * @since 2021-03-02
 */
@Controller
@RequestMapping("/userAddress")
public class UserAddressController {

    @Autowired
    private UserAddressService userAddressService;

    @Autowired
    private CartService cartService;

    /**
     * 删除地址
     */
    @ResponseBody
    @GetMapping("/deleteAddress/{id}/{isdefault}")
    private String deleteAddress(@PathVariable("id")Integer id,@PathVariable("isdefault")Integer isdefault){
        if(isdefault == 1){
            return "false";
        }else{
            userAddressService.removeById(id);
            return "true";
        }
    }

    /**
     * 跳转到修改地址界面
     */
    @GetMapping("/update/{id}")
    private ModelAndView update(@PathVariable("id")Integer id, HttpSession session){

        ModelAndView modelAndView  = new ModelAndView();
        modelAndView.setViewName("userAddressUpdate");

        //根据编号查询地址对象
        UserAddress userAddress = userAddressService.getById(id);

        modelAndView.addObject("userAddress",userAddress);

        //获得登录的用户
        User user = (User) session.getAttribute("user");

        QueryWrapper qw = new QueryWrapper();
        qw.eq("user_id",user.getId());
        //根据用户编号查询出来购物车集合
        modelAndView.addObject("cartList",cartService.findAllCartVOByUserId(user.getId()));

        return modelAndView;
    }

    /**
     * 执行修改地址的操作
     */

    @PostMapping("/doUpdate")
    public ModelAndView doUpdate(UserAddress userAddress,HttpSession session){
        ModelAndView modelAndView  = new ModelAndView();

        //获得登录的用户
        User user = (User) session.getAttribute("user");

        if(userAddressService.updateById(userAddress)){
            QueryWrapper qw = new QueryWrapper();
            qw.eq("user_id",user.getId());
            //根据用户编号查询出来购物车集合
            modelAndView.setViewName("redirect:/user/userAddressList");
            modelAndView.addObject("cartList",cartService.findAllCartVOByUserId(user.getId()));
        }else{
            modelAndView.setViewName("userAddressUpdate");
        }
        return modelAndView;
    }

}

